//
//  AllStudent.cpp
//  宿舍管理系统
//
//  Created by 孟强定 on 2020/6/26.
//  Copyright © 2020 mqd. All rights reserved.
//

#include "list.hpp"

AllStudent::AllStudent(int n):num(n){
    allStudents = new Student[n];
}

void AllStudent::init(int n){
    for(int i=0;i<n;i++)
        allStudents[i].init();
}
void AllStudent::print(){
    int start=0,page=0,allPage=(num-1)/5+1;
    char c=getchar();
    while(1){
        page++;
        std::cout<<"---------------------------------";
        std::cout<<"信息: 第"<<page<<"页/共"<<allPage<<"页"<<std::endl;
        for(int i=start;i<start+5;i++){
            allStudents[i].print();
        }
        start+=5;
        std::cout<<"输入0退出, 回车下一页:";
        char c=getchar();
        for(int i=0;i<3;i++) std::cout<<std::endl;
        if (c=='0') break;
    }
}

Student* AllStudent::findByName(std::string s){
    for(int i=0;i<num;i++){
        if (allStudents[i].getName()==s)
            return &allStudents[i];
    }
    return nullptr;
}

Student* AllStudent::findById(int id){
    for(int i=0;i<num;i++){
        if (allStudents[i].getId()==id)
            return &allStudents[i];
    }
    return nullptr;
}

Student* AllStudent::next(){
    if (num==st) return nullptr;
    return &allStudents[st++];
}
void AllStudent::sortById(){
    auto cmp=[](Student a, Student b){return a.getId()<=b.getId();};
    sort<Student>(allStudents, 0, num-1, cmp);
}
void AllStudent::sortByName(){
    auto cmp=[](Student a, Student b){return a.getName()<=b.getName();};
    sort<Student>(allStudents, 0, num-1, cmp);
}
void AllStudent::sortByRoom(){
    auto cmp=[](Student a, Student b){return a.getRoom()<=b.getRoom();};
    sort<Student>(allStudents, 0, num-1, cmp);
}
template<typename T>
void AllStudent::sort(T *a, int l,int r, bool (*cmp)(T a,T b) ){
    int mid= rand()%(r-l+1)+l;
    int i=l, j=r;
    while(i<j){
        while(i<mid && cmp(a[i],a[mid])) i++;
        std::swap(a[i],a[mid]); mid=i;
        while(mid<j && cmp(a[mid],a[j])) j--;
        std::swap(a[mid],a[j]); mid=j;
    }
    if (l<i-1) sort(a,l,i-1,cmp);
    if (j+1<r) sort(a,j+1,r,cmp);
}
